import { getToken } from '@/utils/storage'
import { Message } from 'element-ui'
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    // { path: '/', redirect: '/dashboard' },
    {
      path: '/',
      component: () => import('@/views/layout'),
      redirect: '/dashboard',
      children: [
        // 二级路由的 path 有两种写法:
        // 1. 绝对路径
        // /dashboard
        // 2. 相对路径 自动拼接上父路由地址 => /dashboard
        // /home/dashboard
        { path: 'dashboard', component: () => import('@/views/dashboard') },
        { path: 'article', component: () => import('@/views/article') }
      ]
    },
    { path: '/login', component: () => import('@/views/login') }
  ]
})

const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  // 排除法
  // 思考: 哪些情况下是直接允许放行的?
  // 1. 有 token
  // 2. 白名单
  // const token = getToken()
  // if (token) return next()
  // if (whiteList.includes(to.path)) return next()
  if (getToken() || whiteList.includes(to.path)) return next()
  next('/login')
  Message.error('请您先登录哦')
})

export default router
